//
//  AppDelegate.swift
//  ShareUmbrella
//
//  Created by Roger on 2017/8/5.
//  Copyright © 2017年 尧尚信息科技. All rights reserved.
//  Roger:18684909663
//

import UIKit
import UserNotifications
import TSMessages
import YSKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    var window: UIWindow?
    var deviceToken: NSString!

    

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        self.window = APP.configWindow()
        UNUserNotificationCenter.current().delegate = self;
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert]) { (success, error) in
            if success {
                print("success")
            } else {
                print("error")
            }
        }
        UIApplication.shared.registerForRemoteNotifications()
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
    
    // 当一个通知被提交到前台的时候，该方法会被调用。// 如果你想在前台显示推送消息，那么你必须返回一个有内容的数组
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        
        let option: UNNotificationPresentationOptions
        
        option = [.alert,.sound]
        
        completionHandler(option)
        
    }
    
    // 第二个方法严格来说只要用户点击消息推送弹出框就会调用。
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        
        // pull out the buried userInfo dictionary
        let userInfo = response.notification.request.content.userInfo
        
        NotificationCenter.default.post(name: RomoteNotifcation, object: nil, userInfo: userInfo)
        completionHandler()
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
        print(token)
        self.deviceToken = token as NSString
        if(Auth.token != ""){
            _ = YSNetWorkManager.provider.requestJSON(YSStructTarget(UserAPI.updatePushToken(pushToken: token, token: Auth.token))).subscribe(onNext: {(data) in
            }, onError: {[weak self](ErrorType) in
                HUD.hide()
                guard let  `self` = self else {
                    return
                }
                self.handle(withError: ErrorType)
            })
        }
    }
    
    //ios8之后，需要添加这个方法
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print("didReceiveRemoteNotification")
    }
}
